import http.client
import urllib
import json
import hashlib
import hmac

import time
import pandas as pd
def getSign(params, secretKey):
    bSecretKey = bytes(secretKey, encoding='utf8')

    sign = ''
    for key in params.keys():
        value = str(params[key])
        sign += key + '=' + value + '&'
    bSign = bytes(sign[:-1], encoding='utf8')

    mySign = hmac.new(bSecretKey, bSign, hashlib.sha512).hexdigest()
    return mySign

def httpGet(url, resource, params=''):
    conn = http.client.HTTPSConnection(url, timeout=10)
    conn.request("GET", resource + '/' + params)
    response = conn.getresponse()
    data = response.read().decode('utf-8')
    return json.loads(data)

def httpPost(url, resource, params, apiKey, secretKey):
     headers = {
            "Content-type" : "application/x-www-form-urlencoded",
            "KEY":apiKey,
            "SIGN":getSign(params, secretKey)
     }

     conn = http.client.HTTPSConnection(url, timeout=10)

     tempParams = urllib.parse.urlencode(params) if params else ''
     print(tempParams)

     conn.request("POST", resource, tempParams, headers)
     response = conn.getresponse()
     data = response.read().decode('utf-8')
     params.clear()
     conn.close()
     return data

class GateIO:
    def __init__(self, url, apiKey, secretKey):
        self.__url = url
        self.__apiKey = apiKey
        self.__secretKey = secretKey

    def kLine(self,param):
        '''[时间，交易量，收盘价，最高价，最低价，开盘价'''
        URL='/api2/1/candlestick2/'
        return httpGet(self.__url,URL,param+'?group_sec=60&range_hour=24')


API_QUERY_URL = 'data.gateio.io'
gate_query = GateIO(API_QUERY_URL, ' ', ' ')

path='/home/hashaki/pycharm-work/testKline.csv'

data=gate_query.kLine('eos_usdt')['data']

time_1=[]
row=[]
vol=[]
close=[]
high=[]
low=[]
open_=[]
for i in data:
    time_1.append(int(i[0])/1000)
    row.append([float(i[1]),float(i[2]),float(i[3]),float(i[4]),float(i[5])])

time_2=[]
for j in time_1:
    time_2.append(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(j)))

del time_1

Kdata=pd.DataFrame(row,index=time_2,columns=['vol','close','high','low','open'])
Kdata.to_csv(path)